from datetime import datetime

import requests
from flask import Flask
from flask_apscheduler import APScheduler

from models.my_model import db, User
from Config import config
from view.data_view import page_data
from view.error_view import page_error

from view.index_view import page_index
from view.post_view import page_post
from view.template_view import page_template
from view.user_view import page_user
from view.comment_view import comment_post
from view.profile_view import page_profile
from view.search_view import page_search
from view.like_view import page_like
app = Flask(__name__)
app.config.from_object(config)

# 初始化数据库
db.init_app(app)

with app.app_context():
    db.create_all()

app.register_blueprint(page_index)
app.register_blueprint(page_post)
app.register_blueprint(page_template)
app.register_blueprint(page_user)
app.register_blueprint(page_error)
app.register_blueprint(comment_post)
app.register_blueprint(page_profile)
app.register_blueprint(page_search)
app.register_blueprint(page_like)
app.register_blueprint(page_data)

app.config['DEBUG'] = True

# 初始化flask_login
from flask_login import LoginManager
login_manager = LoginManager(app)  # 实例化扩展类
@login_manager.user_loader
def load_user(user_id):  # 创建用户加载回调函数，接受用户 ID 作为参数
    user = User.query.get(int(user_id))  # 用 ID 作为 User 模型的主键查询对应的用户
    return user  # 返回用户对象
# 初始化flask_login end

scheduler = APScheduler()
@scheduler.task('interval', id='do_job_1', seconds=120, misfire_grace_time=900)
def job():
    """
    定时任务，刷新词云图
    """
    print(str(datetime.now()) + ' ..... WC image refreshing')
    req = requests.get("http://127.0.0.1:5000/_refresh_and_get_wordcloud")
    if req.status_code == 200:
        print(str(datetime.now()) + '   WC image refreshed')
    print(str(datetime.now()) + ' ..... WC_without_mask image refreshing')
    req = requests.get("http://127.0.0.1:5000/_refresh_and_get_wordcloud/_without_mask")
    if req.status_code == 200:
        print(str(datetime.now()) + '   WC_without_mask image refreshed')



if __name__ == '__main__':

    # it is also possible to enable the API directly
    # scheduler.api_enabled = True
    scheduler.init_app(app)
    scheduler.start()
    app.run(debug=True)